//
//  EeNet.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/12/1.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import UIKit

public enum HTTPError:Error{
    case invalidURL
    case serverError(code:String)
}
public class EasyUploadTask {
    
    public static var tasks:[String:URLSessionUploadTask] = [String:URLSessionUploadTask]()
    
    @discardableResult
    public class func upload(to url:String,tfiles:[TaskFile],params:[String:Any]? = nil,headers:[String:Any]? = nil,handle:@escaping (Any?,Data?, URLResponse?, Error?) -> Swift.Void)->URLSessionUploadTask?{
        
        guard let _url = URL(string: url) else{
            
            handle(nil,nil,nil,HTTPError.invalidURL)
            return nil

        }
    
        
        
        
        let request = NSMutableURLRequest(url: _url)
        request.httpMethod = "POST"
        
        let boundary = "Boundary-\(UUID().uuidString)"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        if let headers = headers
        {
            if request.allHTTPHeaderFields == nil{
                request.allHTTPHeaderFields = [String:String]()
            }
            
            for one in headers
            {
                request.setValue("\(one.value)", forHTTPHeaderField: one.key)
            }
        }
        
        let body = NSMutableData()
        var parameters = [String: Any]()
        
        //        print("params=||\(params)=")
        
        if let ps = params
        {
            parameters = ps
        }
        
        for (key, value) in parameters {
            body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
            body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
            body.append("\(value)\r\n".data(using: String.Encoding.utf8)!)
        }
        
        for tfile in tfiles {
            
            let file_data = tfile.data
            let fname = tfile.fileName
            let mimetype = tfile.mimeType
            let name = tfile.fieldName            
            
            body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
            body.append("Content-Disposition:form-data; name=\"\(name)\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
            body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
            body.append(file_data)
            body.append("\r\n".data(using: String.Encoding.utf8)!)
            body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
            
            
        }
        
        
        request.httpBody = body as Data
        
        let session = URLSession.shared
        session.configuration.httpMaximumConnectionsPerHost = 30
        
        let task_id = UUID().uuidString
        
        let task = session.uploadTask(with: request as URLRequest, from: nil) { (data, response, error) in
            
            DispatchQueue.main.async {
                guard let _data:Data = data, let _:URLResponse = response  , error == nil else {
                    handle(nil,data,response,error)
                    return
                }
                do {
                    let root =  try JSONSerialization.jsonObject(with: _data, options: .mutableContainers)
//                    print("llllll|\(root)")

                    handle(root,data,response,error)
                } catch {
                    handle(nil,data,response,error)
                }
            }
            EasyUploadTask.tasks.removeValue(forKey: task_id)
        }
        
        task.resume()
        EasyUploadTask.tasks[task_id] = task
        
        return task
        
    }
    
    
    
}
extension EasyUploadTask
{
    @discardableResult
    public class func upload(to url:String,tfile:TaskFile,params:[String:Any]? = nil,headers:[String:Any]? = nil,handle:@escaping (Any?,Data?, URLResponse?, Error?) -> Swift.Void)->URLSessionUploadTask{
        
        let _url = URL(string: url)
        
        
        let request = NSMutableURLRequest(url: _url!)
        //        request.allHTTPHeaderFields = JoTask.headerCreator!()
        request.httpMethod = "POST"
        
        let boundary = "Boundary-\(UUID().uuidString)"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        
        let file_data = tfile.data
        
        let body = NSMutableData()
        
        var parameters = [String: Any]()
        if let headers = headers
        {
            if request.allHTTPHeaderFields == nil{
                request.allHTTPHeaderFields = [String:String]()
            }
            
            for one in headers
            {
                request.setValue("\(one.value)", forHTTPHeaderField: one.key)
            }
        }
        
        
        if let ps = params
        {
            parameters = ps
        }
        
        for (key, value) in parameters {
            body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
            body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
            body.append("\(value)\r\n".data(using: String.Encoding.utf8)!)
        }
        
        
        
        
        let fname = tfile.fileName
        let mimetype = tfile.mimeType
        let name = tfile.fieldName
        
        
        body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
        body.append("Content-Disposition:form-data; name=\"\(name)\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
        body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
        body.append(file_data)
        body.append("\r\n".data(using: String.Encoding.utf8)!)
        body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
        //        print("=----||\(body)")
        request.httpBody = body as Data
        
        let session = URLSession.shared
        session.configuration.httpMaximumConnectionsPerHost = 30
        
        let task_id = UUID().uuidString
        let task = session.uploadTask(with: request as URLRequest, from: nil) { (data, response, error) in
            DispatchQueue.main.async {
                guard let _data:Data = data, let _:URLResponse = response  , error == nil else {
                    handle(nil,data,response,error)
                    return
                }
                do {
                    
                    let root =  try JSONSerialization.jsonObject(with: _data, options: .mutableContainers)
                    handle(root,data,response,error)
              
                } catch {
                    handle(nil,data,response,error)
                }
            }
            
            EasyUploadTask.tasks.removeValue(forKey: task_id)
        }
        
        task.resume()
        
        EasyUploadTask.tasks[task_id] = task

        return task
        
        
        
    }
    
    
    
    
}
